package org.zjvis.datascience.service.cleanup;

import java.util.BitSet;

/**
 * @description   类似于布隆过滤器
 *                对BitSet的扩展,支持Long类型.
 *                最大一次性过滤Integer.MAX_VALUE个
 * @date 2021-12-01
 */
public class ExpandBitSet {

    private BitSet lowBitSet;

    private BitSet highBitSet;

    private BitSet intBitSet;

    public ExpandBitSet() {
        this.lowBitSet = new BitSet();
        this.highBitSet = new BitSet();
        this.intBitSet = new BitSet();
    }

    public void set(long bitIndex) {
        if (bitIndex < 0)
            throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
        if (bitIndex <= Integer.MAX_VALUE) {
            intBitSet.set((int) bitIndex);
            return;
        }
        int low = (int) bitIndex & Integer.MAX_VALUE;
        int high = (int) (bitIndex >> 31);
        lowBitSet.set(low);
        highBitSet.set(high);
    }

    public boolean get(long bitIndex) {
        if (bitIndex < 0)
            throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
        if (bitIndex <= Integer.MAX_VALUE) {
            return intBitSet.get((int) bitIndex);
        }
        int low = (int) bitIndex & Integer.MAX_VALUE;
        int high = (int) (bitIndex >> 31);
        return highBitSet.get(high) & lowBitSet.get(low);
    }

}
